﻿@typeparam _Yuan
@inject IHttpClientFactory ClientFactory
@inject IJSRuntime JSRuntime
<Button OnClick="ToExcel2" Type="primary" Style="margin-bottom:16px">
    下载
</Button>
<script>
    window.saveAsFile2 = function (byteBase64) {
        const url = window.URL.createObjectURL(new Blob([byteBase64]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'output.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }  
    window.saveAsFile = function (fileName, byteBase64) {
        const link = document.createElement('a');
        link.href = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + byteBase64;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
</script>
@code {
    [Parameter]
    public List<_Yuan> Items { get; set; }

    private async Task ToExcel2()
    {
        var client = ClientFactory.CreateClient();
        if (Items.Count > 0)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync("C_USER/ExportToExcel", Items);
            if (response.IsSuccessStatusCode)
            {
                // 读取响应内容为字节数组
                byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
                // 将字节数组转换为 Base64 字符串
                string base64String = Convert.ToBase64String(fileBytes);
                // 调用 JavaScript 函数保存文件
                await JSRuntime.InvokeVoidAsync("saveAsFile", "filename.xlsx", base64String);
            }
        }
    }

    protected override void OnInitialized()
    {
        ToExcel2();


    }
}